package com.gehj.imageloder;

import android.app.Notification;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SimpleAdapter;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.NotificationTarget;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;

import org.jetbrains.annotations.NotNull;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.withCrossFade;

/**
 * 图处加载类，外界唯一调用类,直持为view,notifaication,appwidget加载图片
 * 类似与okhttp可以统一处理glide 个性化，图片下载啥的直接在代码中使用glide即可
 *
 * TODO 将来这个类封装 图片选择框架
 */
public class ImageLoaderManager {

    private ImageLoaderManager() {
    }

    public static ImageLoaderManager getInstance() {
        return SingletonHolder.instance;
    }

    private static class SingletonHolder {
        private static ImageLoaderManager instance = new ImageLoaderManager();
    }

    /**
     * 为notification加载图
     */
    public void displayImageForNotification(Context context, RemoteViews rv, int id,
                                            Notification notification, int NOTIFICATION_ID, String url) {
        this.displayImageForTarget(context,
                initNotificationTarget(context, id, rv, notification, NOTIFICATION_ID), url);
    }

    /**
     * 不带回调的加载
     */
    public void displayImageForView(ImageView imageView, String url) {
        this.displayImageForView(imageView, url, null);
    }

    /**
     * 带回调的加载图片方法
     */
    public void displayImageForView(ImageView imageView, String url,
                                    CustomRequestListener requestListener) {
        Glide.with(imageView.getContext())
                .asBitmap()
                .load(url)
                .apply(initCommonRequestOption())
                .transition(withCrossFade())
                .listener(requestListener)
                .into(imageView);
    }

    /**
     * 加载圆形图片 没必要，glide自己有，圆角，圆形
     */
    public void displayImageForCircle(final ImageView imageView, String url) {
        Glide.with(imageView.getContext())
                .asBitmap()//需要bitmap才能有动画
                .load(url)
                .transition(withCrossFade()) //动画效果
                .apply(initCommonRequestOption()) //设置一些占位，错误，缓存策略等
                .transform(new RoundedCorners(20))//圆角
                //.transform(new CircleCrop());//圆形
                .into(imageView);
    }

    /**
     * 给ViewGroup设置背景 不一定需要模糊处理
     * @param group
     * @param url
     * @param isBlur 是否需要毛玻璃效果
     *
     */
    public void displayImageForViewGroup(final ViewGroup group, String url,Boolean isBlur) {
        RequestBuilder requestBuilder =
                Glide.with(group.getContext())
                .asBitmap()
                .load(url)
                .apply(initCommonRequestOption());

        if (isBlur){
            requestBuilder.into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull @NotNull Bitmap resource,
                                            @Nullable @org.jetbrains.annotations.Nullable
                                                    Transition transition) {

                    final Bitmap res = resource;
                    Observable.just(resource)//rxjava
                            .map(new Function<Bitmap, Drawable>() {
                                @Override
                                public Drawable apply(Bitmap bitmap) { //把bitmap转化成drawable
                                    Drawable drawable = new BitmapDrawable(
                                            //高斯模糊,耗时操作
                                            Utils.doBlur(res, 100, true)
                                    );
                                    return drawable;
                                }
                            })
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Consumer<Drawable>() {
                                @Override
                                public void accept(Drawable drawable) throws Exception {
                                    group.setBackground(drawable);
                                }
                            });
                }
            });

       }else {
            requestBuilder.into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(@NonNull @NotNull Bitmap resource, @Nullable @org.jetbrains.annotations.Nullable Transition<? super Bitmap> transition) {
                    Drawable drawable = new BitmapDrawable(resource);
                    group.setBackground(drawable);
                }
            });
        }

    }

    /**
     * 为非view加载图片
     */
    private void displayImageForTarget(Context context, Target target, String url) {
        this.displayImageForTarget(context, target, url, null);
    }

    /**
     * 为非view加载图片
     */
    private void displayImageForTarget(Context context, Target target, String url,
                                       CustomRequestListener requestListener) {
        Glide.with(context)
                .asBitmap()
                .load(url)
                .apply(initCommonRequestOption())
                .transition(withCrossFade())
                .fitCenter()
                .listener(requestListener)
                .into(target);
    }

    /**
     * 初始化Notification Target
     */
    private NotificationTarget initNotificationTarget(Context context, int id, RemoteViews rv,
                                                      Notification notification, int NOTIFICATION_ID) {
        NotificationTarget notificationTarget =
                new NotificationTarget(context, id, rv, notification, NOTIFICATION_ID);
        return notificationTarget;
    }

    private RequestOptions initCommonRequestOption() {
        RequestOptions options = new RequestOptions();
        options.placeholder(R.mipmap.b4y)
                .error(R.mipmap.b4y)
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .skipMemoryCache(false) //启用内存缓存
                .priority(Priority.NORMAL);
        return options;
    }
}
